package br.unipar.bancodedados.manager.impl;

import br.unipar.bancodedados.entidade.Categoria;
import br.unipar.bancodedados.manager.ConnectionSingleton;
import br.unipar.bancodedados.manager.CategoriaManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class JdbcCategoriaManagerImpl implements CategoriaManager {

    private static JdbcCategoriaManagerImpl instance;

    public static CategoriaManager getInstance() {
        if (instance == null) {
            instance = new JdbcCategoriaManagerImpl();
        }
        return instance;
    }

    private JdbcCategoriaManagerImpl() {

    }

    @Override
    public void salvar(Categoria categoria) {
        try {
            Statement stmt = ConnectionSingleton.getInstance().createStatement();

            String sql = String.format(
                    "insert into Categoria(nome) values ('%s')",
                    categoria.getNome());
            
            stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);

            ResultSet rs = stmt.getGeneratedKeys();
            rs.next();
            Long id = rs.getLong(1);
            categoria.setId(id);

            stmt.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Categoria> listar() {
        List<Categoria> list = new ArrayList<Categoria>();

        try {
            Statement stmt = ConnectionSingleton.getInstance().createStatement();

            String sql = "select id, nome from Categoria";
            ResultSet result = stmt.executeQuery(sql);

            while (result.next()) {
                Categoria categoria = new Categoria();
                categoria.setId(result.getLong("id"));
                categoria.setNome(result.getString("nome"));

                list.add(categoria);
            }

            stmt.close();
        } catch(Exception e) {
            e.printStackTrace();
        }

        return list;
    }

}
